import random
import time
from datetime import datetime

from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.support.wait import WebDriverWait

from compements.assemblies.introducing_medication import introducing_medication


# 函数：根据不同优先级选择数据
def select_data_for_field(field_name, new_sf_date, mz_data, tj_data, mb_data):
    selected_data = None
    from_mz = False  # 标志位，表示数据是否来自门诊
    new_sf_date_dt = datetime.strptime(new_sf_date, '%Y-%m-%d')

    # 1. 优先选择与新建的随访日期一致的门诊数据
    for mz in mz_data:
        if mz.get('随访日期:') == new_sf_date:  # 使用get避免KeyError
            selected_data = mz.get(field_name)  # 使用get避免KeyError
            if selected_data is not None and selected_data != "" and selected_data != "未查":
                from_mz = True  # 数据来自门诊
                break

    # 2. 如果没有，选择45天内的体检数据
    if not from_mz and (selected_data is None or selected_data == "" or selected_data == "未查"):
        tj_date = tj_data.get('体检日期')  # 使用get避免KeyError
        if tj_date:
            tj_date_dt = datetime.strptime(tj_date, '%Y-%m-%d')
            # 计算日期差（取绝对值）
            date_diff = abs((tj_date_dt - new_sf_date_dt).days)
            # 检查是否在45天内（包含45天）
            if date_diff <= 60:
                selected_data = tj_data.get(field_name)  # 使用get避免KeyError

    # 3. 如果没有符合条件的门诊数据和体检数据，选择档案数据
    if not from_mz and (selected_data is None or selected_data == "" or selected_data == "未查"):
        selected_data = mb_data.get(field_name)  # 使用get避免KeyError

    return selected_data, from_mz  # 返回数据和标志位


def get_new_sf_data(mb_data, mz_data, tj_data, n_sf_time, sf_data, sfzh, record, headers):
    # 根据规则为每个字段选择数据
    selected_data = {"随访日期": n_sf_time}

    # 身高
    height, from_mz = select_data_for_field('身高', n_sf_time, mz_data, tj_data, mb_data)
    existing_height_values = [(date, float(v['身高'])) for date, v in sf_data.items() if
                              v['身高'] is not None and v['身高'] != "未查"]
    existing_height_values.sort(key=lambda x: datetime.strptime(x[0], '%Y-%m-%d'))

    # 检查身高差距 - 只有在有历史数据时才比较
    if height is not None and existing_height_values:
        last_height = existing_height_values[-1][1]
        height_diff = abs(float(height) - last_height)
        if height_diff > 0:  # 差距大于10cm
            # 记录异常情况
            with open("./执行结果/身高体重异常记录.txt", "a+", encoding="utf-8") as f:
                f.write(
                    f"{sfzh}---身高异常: 本次身高({height}cm)与最近一次身高({last_height}cm)差距大于0cm (差距: {height_diff:.1f}cm)\n")
                f.write(f"  最近一次随访时间: {existing_height_values[-1][0]}\n")
                f.write(f"  历史身高数据: {[(d, f'{v}cm') for d, v in existing_height_values]}\n")
                f.write(f"  数据来源: {'门诊' if from_mz else '档案/体检'}\n\n")

    selected_data["身高"] = height

    if "身高" in headers:
        selected_data["身高"] = record["身高"]
        print("身高读表:", record["身高"])

    # 体重
    weight, from_mz = select_data_for_field('体重', n_sf_time, mz_data, tj_data, mb_data)
    existing_weight_values = [(date, float(v['体重'])) for date, v in sf_data.items() if
                              v['体重'] is not None and v['体重'] != "未查"]
    existing_weight_values.sort(key=lambda x: datetime.strptime(x[0], '%Y-%m-%d'))
    print("根据档案、门诊、体检选出的体重:", weight)
    print("以往随访的体重:", existing_weight_values)

    # 检查体重差距 - 只有在有历史数据时才比较
    if weight is not None and existing_weight_values:
        last_weight = existing_weight_values[-1][1]
        weight_diff = abs(float(weight) - last_weight)
        if weight_diff > 10:  # 差距大于10kg
            # 记录异常情况
            with open("./执行结果/身高体重异常记录.txt", "a+", encoding="utf-8") as f:
                f.write(f"{sfzh}---体重异常: 本次体重({weight}kg)与最近一次体重({last_weight}kg)差距大于10kg (差距: {weight_diff:.1f}kg)\n")
                f.write(f"  最近一次随访时间: {existing_weight_values[-1][0]}\n")
                f.write(f"  历史体重数据: {[(d, f'{v}kg') for d, v in existing_weight_values]}\n")
                f.write(f"  数据来源: {'门诊' if from_mz else '档案/体检'}\n\n")

    if weight in existing_weight_values:
        if not existing_weight_values:  # 如果是第一次随访
            change = random.choice([-3.0, -2.0, -1.0, 1.0, 2.0, 3.0])
            new_weight = float(weight) + float(change)
            new_weight = round(new_weight, 1)
        else:
            # 获取最近一次随访的体重
            last_weight = existing_weight_values[-1][1]
            print("最近一次随访的体重:", last_weight)
            # 在±2.5kg范围内随机选择变化量
            change = random.uniform(-2.5, 2.5)
            new_weight = last_weight + change
            # 四舍五入到小数点后1位
            new_weight = round(new_weight, 1)
        selected_data["体重"] = new_weight
    else:
        selected_data["体重"] = weight

    if "体重" in headers:
        selected_data["体重"] = record["体重"]
        print("体重读表:", record["体重"])

    # 收缩压
    sbp, from_mz = select_data_for_field('收缩压', n_sf_time, mz_data, tj_data, mb_data)
    sbp = int(float(sbp))
    existing_systolic_values = {int(v['收缩压']) for v in sf_data.values() if
                                v['收缩压'] is not None and v['收缩压'] != "未查"}
    print("根据档案、门诊、体检选出的收缩压:", sbp)
    print("以往随访的收缩压:", existing_systolic_values)

    if not from_mz:  # 如果数据不是来自门诊，才进行后续的判断和随机生成
        if sbp in existing_systolic_values or int(float(sbp)) > 138 or int(float(sbp)) < 115:
            sbp = random.randint(115, 138)
            while sbp in existing_systolic_values:
                sbp = random.randint(115, 138)
    else:
        sbp = sbp  # 数据来自门诊，直接使用
    selected_data["收缩压"] = sbp

    if "左侧血压(收缩压)" in headers and "右侧血压(收缩压)" in headers:
        left_value = record["左侧血压(收缩压)"]
        right_value = record["右侧血压(收缩压)"]

        # 尝试将两侧血压值转换为数值
        left_valid = True
        right_valid = True
        left_num = 120
        right_num = 120

        try:
            left_num = float(left_value)
        except (ValueError, TypeError):
            left_valid = False

        try:
            right_num = float(right_value)
        except (ValueError, TypeError):
            right_valid = False

        # 根据有效性选择血压值
        if left_valid and right_valid:
            # 两侧都有效时选择较高的
            if left_num >= right_num:
                selected_data["收缩压"] = left_value
                print(f"收缩压读表（左侧较高）: {left_value}")
            else:
                selected_data["收缩压"] = right_value
                print(f"收缩压读表（右侧较高）: {right_value}")

        elif left_valid:
            # 仅左侧有效
            selected_data["收缩压"] = left_value
            print(f"收缩压读表（右侧无效，使用左侧）: {left_value}")

        elif right_valid:
            # 仅右侧有效
            selected_data["收缩压"] = right_value
            print(f"收缩压读表（左侧无效，使用右侧）: {right_value}")

        else:
            # 两侧都无效时使用左侧原始值
            selected_data["收缩压"] = sbp

    # 舒张压
    dbp, from_mz = select_data_for_field('舒张压', n_sf_time, mz_data, tj_data, mb_data)
    dbp = int(float(dbp))
    existing_diastolic_values = {int(v['舒张压']) for v in sf_data.values() if
                                 v['舒张压'] is not None and v['舒张压'] != "未查"}
    print("根据档案、门诊、体检选出的舒张压:", dbp)
    print("以往随访的舒张压:", existing_diastolic_values)

    if not from_mz:  # 如果数据不是来自门诊，才进行后续的判断和随机生成
        if dbp in existing_diastolic_values or int(float(dbp)) > 85 or int(float(dbp)) < 60:
            min_diastolic = max(65, int(float(sbp)) - 60)
            max_diastolic = min(85, int(float(sbp)))
            dbp = random.randint(min_diastolic, max_diastolic)
            while dbp in existing_diastolic_values:
                dbp = random.randint(min_diastolic, max_diastolic)
    else:
        dbp = dbp  # 数据来自门诊，直接使用
    selected_data["舒张压"] = dbp

    if "左侧血压(舒张压)" in headers and "右侧血压(舒张压)" in headers:
        left_value = record["左侧血压(舒张压)"]
        right_value = record["右侧血压(舒张压)"]

        # 尝试将两侧舒张压值转换为数值
        left_valid = True
        right_valid = True
        left_num = 80
        right_num = 80

        try:
            left_num = float(left_value)
        except (ValueError, TypeError):
            left_valid = False

        try:
            right_num = float(right_value)
        except (ValueError, TypeError):
            right_valid = False

        # 根据有效性选择舒张压值
        if left_valid and right_valid:
            # 两侧都有效时选择较高的
            if left_num >= right_num:
                selected_data["舒张压"] = left_value
                print(f"舒张压读表（左侧较高）: {left_value}")
            else:
                selected_data["舒张压"] = right_value
                print(f"舒张压读表（右侧较高）: {right_value}")

        elif left_valid:
            # 仅左侧有效
            selected_data["舒张压"] = left_value
            print(f"舒张压读表（右侧无效，使用左侧）: {left_value}")

        elif right_valid:
            # 仅右侧有效
            selected_data["舒张压"] = right_value
            print(f"舒张压读表（左侧无效，使用右侧）: {right_value}")

        else:
            # 两侧都无效时使用左侧原始值
            selected_data["舒张压"] = left_value
            print(f"警告：舒张压两侧都无效！使用左侧原始值: {left_value}")

    # 心率
    heart_rate, from_mz = select_data_for_field('心率', n_sf_time, mz_data, tj_data, mb_data)
    existing_heart_rate_values = {int(v['心率']) for v in sf_data.values() if v['心率'] != "未查"}
    print("根据档案、门诊、体检选出的心率:", heart_rate)
    print("以往随访的心率:", existing_heart_rate_values)

    if not from_mz:  # 如果数据不是来自门诊，才进行后续的判断和随机生成
        if heart_rate is None or heart_rate in existing_heart_rate_values:
            heart_rate = random.randint(60, 100)
            while heart_rate in existing_systolic_values:
                heart_rate = random.randint(60, 100)
    else:
        heart_rate = heart_rate  # 数据来自门诊，直接使用
    selected_data["心率"] = heart_rate

    if "心率" in headers:
        selected_data["心率"] = record["心率"]
        print("心率读表:", record["心率"])

    # 腰围
    waistline, from_mz = select_data_for_field('腰围', n_sf_time, mz_data, tj_data, mb_data)
    change = random.choice([-5, -4, -3, -2, -1, 1, 2, 3, 4, 5])
    if isinstance(waistline, str):
        waistline = int(float(waistline))
    new_waistline = waistline + change
    selected_data["腰围"] = new_waistline

    if "腰围" in headers:
        selected_data["腰围"] = record["腰围"]
        print("腰围读表:", record["腰围"])

    # 日吸烟量
    smoke_amount, from_mz = select_data_for_field('日吸烟量', n_sf_time, mz_data, tj_data, mb_data)
    selected_data["日吸烟量"] = smoke_amount

    # 日饮酒量
    # drink_amount, from_mz = select_data_for_field('日饮酒量', n_sf_time, mz_data, tj_data, mb_data)
    selected_data["日饮酒量"] = mb_data["日饮酒量"]

    # 运动次数
    sport_times, from_mz = select_data_for_field('运动次数', n_sf_time, mz_data, tj_data, mb_data)
    selected_data["运动次数"] = sport_times

    # 运动时间
    sport_time, from_mz = select_data_for_field('运动时间', n_sf_time, mz_data, tj_data, mb_data)
    selected_data["运动时间"] = sport_time

    # 主食量
    food_amount, from_mz = select_data_for_field('主食量', n_sf_time, mz_data, tj_data, mb_data)
    try:
        selected_data["主食量"] = int(float(food_amount)) * 3
    except:
        selected_data["主食量"] = 300

    # 摄盐情况
    salt, from_mz = select_data_for_field('摄盐情况', n_sf_time, mz_data, tj_data, mb_data)
    selected_data["摄盐情况"] = salt

    # 空腹血糖
    has_diabetes = '糖尿病' in mb_data.get('疾病史', '')
    glucose_range = (5.9, 6.9) if has_diabetes else (5.2, 6.1)
    glucose, from_mz = select_data_for_field('空腹血糖', n_sf_time, mz_data, tj_data, mb_data)
    existing_glucose_values = {float(v['空腹血糖']) for v in sf_data.values() if v['空腹血糖'] != "未查"}

    if not from_mz:
        # 先将 glucose 转换为浮点数（如果不是 None）
        if glucose is not None:
            try:
                glucose = float(glucose)
            except (ValueError, TypeError):
                glucose = None

        # 检查 glucose 是否为 None 或已经存在于 existing_glucose_values 中
        if glucose is None or glucose in existing_glucose_values or not (glucose_range[0] <= glucose <= glucose_range[1]):
            # 如果不在范围内或重复，重新生成一个不重复且在范围内的值
            glucose = round(random.uniform(*glucose_range), 1)
            while glucose in existing_glucose_values or not (glucose_range[0] <= glucose <= glucose_range[1]):
                glucose = round(random.uniform(*glucose_range), 1)
        else:
            glucose = glucose
    else:
        mz_glucose = float(glucose)
        print(f"来源于门诊的空腹血糖:{mz_glucose}")
        if mz_glucose >= 7.0:
            print("门诊空腹血糖大于7.0，重新生成")
            glucose = round(random.uniform(*glucose_range), 1)
            while glucose in existing_glucose_values or not (glucose_range[0] <= glucose <= glucose_range[1]):
                glucose = round(random.uniform(*glucose_range), 1)
            with open("执行结果/门诊空腹血糖大于7.0，重新生成名单.txt", "a+", encoding="utf-8") as f:
                f.write(f"{sfzh}---门诊空腹血糖{mz_glucose}大于7.0---重新选择为{glucose}\n")
        else:
            glucose = mz_glucose
        glucose = glucose
    selected_data["空腹血糖"] = glucose

    if "空腹血糖(mmol/L)" in headers:
        selected_data["空腹血糖"] = str(record["空腹血糖(mmol/L)"]).replace("nan", "未查")
        print("空腹血糖读表:", selected_data["空腹血糖"])

    selected_data["糖化血红蛋白"] = '未查'
    if "糖化血红蛋白" in headers:
        selected_data["糖化血红蛋白"] = str(record["糖化血红蛋白"]).replace("nan", "未查")
        print("糖化血红蛋白读表:", selected_data["糖化血红蛋白"])

    selected_data["总胆固醇"] = '未查'
    if "总胆固醇" in headers:
        selected_data["总胆固醇"] = str(record["总胆固醇"]).replace("nan", "未查")
        print("总胆固醇读表:", selected_data["总胆固醇"])

    selected_data["甘油三酯"] = '未查'
    if "甘油三酯" in headers:
        selected_data["甘油三酯"] = str(record["甘油三酯"]).replace("nan", "未查")
        print("甘油三酯读表:", selected_data["甘油三酯"])

    selected_data["血清低密度脂蛋白胆固醇"] = '未查'
    if "血清低密度脂蛋白胆固醇" in headers:
        selected_data["血清低密度脂蛋白胆固醇"] = str(record["血清低密度脂蛋白胆固醇"]).replace("nan", "未查")
        print("血清低密度脂蛋白胆固醇读表:", selected_data["血清低密度脂蛋白胆固醇"])

    selected_data["血清高密度脂蛋白胆固醇"] = '未查'
    if "血清高密度脂蛋白胆固醇" in headers:
        selected_data["血清高密度脂蛋白胆固醇"] = str(record["血清高密度脂蛋白胆固醇"]).replace("nan", "未查")
        print("血清高密度脂蛋白胆固醇读表:", selected_data["血清高密度脂蛋白胆固醇"])

    selected_data["血尿素氮"] = '未查'
    if "血尿素氮" in headers:
        selected_data["血尿素氮"] = str(record["血尿素氮"]).replace("nan", "未查")
        print("血尿素氮读表:", selected_data["血尿素氮"])

    selected_data["血清肌酐"] = '未查'
    if "血清肌酐" in headers:
        selected_data["血清肌酐"] = str(record["血清肌酐"]).replace("nan", "未查")
        print("血清肌酐读表:", selected_data["血清肌酐"])

    selected_data["尿检"] = '未查'
    if "尿蛋白" in headers:
        urinalysis = [f'尿蛋白{str(record["尿蛋白"]).replace("nan", "未查")}',
                      f'尿糖{str(record["尿糖"]).replace("nan", "未查")}',
                      f'尿潜血{str(record["尿潜血"]).replace("nan", "未查")}',
                      f'尿酮体{str(record["尿酮体"]).replace("nan", "未查")}']
        selected_data["尿检"] = ','.join(urinalysis)
        if urinalysis == '尿蛋白未查,尿糖未查,尿潜血未查,尿酮体未查':
            selected_data["尿检"] = "无"
        print("尿检读表:", selected_data["尿检"])

    selected_data["尿微量白蛋白"] = '未查'
    if "尿微量白蛋白" in headers:
        selected_data["尿微量白蛋白"] = str(record["尿微量白蛋白"]).replace("nan", "未查")
        print("尿微量白蛋白读表:", selected_data["尿微量白蛋白"])

    selected_data["心电图"] = '未检查'
    if "心电图" in headers:
        electrocardiogram = str(record["心电图"]).replace("nan", "未检查")
        electrocardiogram_box = str(record["心电图编辑框"]).replace("nan", "未查")
        if electrocardiogram == "异常":
            selected_data["心电图"] = electrocardiogram_box
        elif electrocardiogram == "正常":
            selected_data["心电图"] = "正常"
        elif electrocardiogram == "未检查":
            selected_data["心电图"] = "未检查"
        print("心电图读表:", selected_data["心电图"])

    selected_data["其他辅助检查"] = '未检查'
    abdominal_B = ''
    hemoglobin = ''
    if "腹部B超" in headers:
        abdominal = str(record["腹部B超"]).replace("nan", "未检查")
        abdominal_box = str(record["腹部B超编辑框"]).replace("nan", "未查")
        if abdominal == "异常":
            abdominal_B = f"腹部B超:{abdominal_box}"
        elif abdominal == "正常":
            abdominal_B = f"腹部B超:正常"
        elif abdominal == "未检查":
            abdominal_B = f"腹部B超:未检查"
    if "糖化血红蛋白" in headers:
        hemoglobin = f'糖化血红蛋白:{str(record["糖化血红蛋白"]).replace("nan", "未查")}'
    if abdominal_B != '' and hemoglobin != '糖化血红蛋白:':
        selected_data["其他辅助检查"] = abdominal_B + ',' + hemoglobin
    else:
        selected_data["其他辅助检查"] = abdominal_B
    print("其他辅助检查读表:", selected_data["其他辅助检查"])

    selected_data["症状"] = "无症状"
    selected_data["症状其他编辑框"] = ''

    if "症状" in headers:
        selected_data["症状"] = str(record["症状"]).replace("nan", "无症状")
        print("症状读表:", selected_data["症状"])

        selected_data["症状其他编辑框"] = str(record["症状其他编辑框"]).replace("nan", "")
        print("症状其他编辑框读表:", selected_data["症状其他编辑框"])

    selected_data["是否咳嗽、咳痰≥2周"] = "无"
    if "是否咳嗽、咳痰≥2周" in headers:
        selected_data["是否咳嗽、咳痰≥2周"] = str(record["是否咳嗽、咳痰≥2周"]).replace("nan", "无")
        print("是否咳嗽、咳痰≥2周读表:", selected_data["是否咳嗽、咳痰≥2周"])

    selected_data["是否痰中带血或咯血"] = "无"
    if "是否痰中带血或咯血" in headers:
        selected_data["是否痰中带血或咯血"] = str(record["是否痰中带血或咯血"]).replace("nan", "无")
        print("是否痰中带血或咯血读表:", selected_data["是否痰中带血或咯血"])

    return selected_data

